package com.zqs.controller;

import com.fasterxml.jackson.databind.util.ClassUtil;
import com.google.code.kaptcha.Producer;
import com.zqs.controller.ex.FileEmptyException;
import com.zqs.controller.ex.FileSizeException;
import com.zqs.controller.ex.FileTypeException;
import com.zqs.controller.ex.FileUploadIOException;
import com.zqs.entity.Password;
import com.zqs.entity.User;
import com.zqs.service.UserService;
import com.zqs.service.ex.KaptchaException;
import com.zqs.utils.JsonResult;
import javafx.application.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/users")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @Resource
    private Producer kaptchaProducer;

    // 注册
    @PostMapping("/reg")
    public JsonResult<Void> reg(User user){
        userService.reg(user);
        return new JsonResult<>(OK);
    }

    // 登录
    @GetMapping("/login")
    public JsonResult<User> login(User user, String verifyCode, HttpSession session){

        String kaptchaVerifyCode = (String) session.getAttribute("kaptchaVerifyCode");
        if (!kaptchaVerifyCode.equals(verifyCode)){
            throw new KaptchaException("验证码错误!");
        }
        User data = userService.login(user.getUsername(), user.getPassword());
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        System.out.println("data:" + data);
        Integer uid = (Integer) session.getAttribute("uid");
        System.out.println(uid);
        return new JsonResult<>(OK,data);
    }

    // 验证码
    @GetMapping("/verify_code")
    public void createVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache_Control", "no-store,no-cache,must-revalidate");
        response.setHeader("Cache_Control", "post-check=0,pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/png");
        // 生成验证码字符文本
        String text = kaptchaProducer.createText();
        request.getSession().setAttribute("kaptchaVerifyCode", text);
        System.out.println("1:" + request.getSession().getAttribute("kaptchaVerifyCode"));
        BufferedImage image = kaptchaProducer.createImage(text);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "png", outputStream);
        // 输出和关闭输出
        outputStream.flush();
        outputStream.close();
    }

//    //补全用户信息
//    @PostMapping("/update_info")
//    public JsonResult<Void> updateInfo(User user,HttpSession session){
//        Integer uid = getSessionUid(session);
//        String username = getSessionUsername(session);
//        userService.updateUserInfo(user,uid,username);
//        return new JsonResult<>(OK);
//    }

    //用户个人信息展示页
    @GetMapping("/user_info")
    public JsonResult<User> userInfo(HttpSession session){
        String username = getSessionUsername(session);
        User data = userService.userInfo(username);
        return new JsonResult<>(OK,data);
    }

    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;

    public static final List<String> AVATAR_TYPE = new ArrayList<>();
    static  {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/gif");
        AVATAR_TYPE.add("image/bmp");
    }

    //补全用户信息（头像,电话,邮箱,性别）  参数：form-data{file:头像文件,phone,email,gender}
    @PostMapping("/update_info")
    public JsonResult<String> updateInfo(User user,HttpSession session, MultipartFile file){
        System.out.println(file);
        // 判断文件是否为空
        if (file.isEmpty()){
            throw new FileEmptyException("文件为空!");
        }
        // 判断文件的大小
        if (file.getSize() > AVATAR_MAX_SIZE){
            throw new FileSizeException("文件超出限制!");
        }
        // 判断文件的类型
        String contentType = file.getContentType();
        // contains 判断一个支付串中是否包含 某个内容
        if (!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException("文件类型不支持!");
        }
        // 上传的文件形式：../upload/..png
//        String parent = session.getServletContext().getRealPath("upload");
        String path = "C:\\Users\\张青山\\Desktop\\毕设\\zqs-bs\\src\\main\\resources\\static\\avatar";

        // 让File对象指向parent这个路径，看File是否存在
        File dir = new File(path);
        if (!dir.exists()){ // 检测目录是否存在
            dir.mkdirs(); // 创建当前目录
        }
        // 获取该文件的名称（例：test.png），用uuid生成一个随机的字符串作为文件的新名称（避免用户上传的图片名称一致）
        String originalFilename = file.getOriginalFilename(); // 获取文件的名称
        System.out.println(originalFilename);
        int index = originalFilename.lastIndexOf("."); // 获取" . "该处的索引
        String suffix = originalFilename.substring(index); // 从" . "开始截取字符串
        String prefix = UUID.randomUUID().toString().toUpperCase(); // uuid随机生成文件的前缀
        String filename ="/" + prefix + suffix;
        // 在dir下创建一个filename的空文件，用于接受MultipartFile file
        File dest = new File(dir, filename);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常!");
        }

        String username = getSessionUsername(session);
        Integer uid = getSessionUid(session);
        String avatar = "/upload" + filename;
        user.setAvatar(avatar);
        userService.updateUserInfo(user,uid,username);
        return new JsonResult<>(OK,avatar);
    }

    // 修改密码
    @PostMapping("/update_password")
    public JsonResult<Void> updatePassword(@RequestBody Password password, HttpSession session){
        String username = getSessionUsername(session);
        Integer uid = getSessionUid(session);
        System.out.println(uid);
        userService.updatePassword(password.getOldPassword(),password.getNewPassword(),username,uid);
        return new JsonResult<>(OK);
    }
}
